<template>
    <div class="layout-padding">
        <splitpanes horizontal>
            <pane size="50">
                <div class="layout-padding-auto layout-padding-view">
                    <!--查询表单-->
                    <el-form :model="state.queryForm" ref="queryRef" :inline="true" @keyup.enter="getDataList">
                        <el-form-item :label="$t('poheader.poCode')" prop="materialCode">
                          <el-input v-model="state.queryForm.poCode" clearable/>
                        </el-form-item>
                        <el-form-item :label="$t('poheader.contractNumber')" prop="materialCode">
                          <el-input v-model="state.queryForm.contractNumber" clearable/>
                        </el-form-item>
                        <el-form-item :label="$t('so.materialcode')" prop="materialCode">
                            <el-input v-model="state.queryForm.materialCode" clearable/>
                        </el-form-item>
                        <el-form-item :label="$t('so.materialname')" prop="materialName">
                            <el-input v-model="state.queryForm.materialName" clearable/>
                        </el-form-item>
<!--                        <el-form-item :label="$t('podetail.requiredDate')" prop="requiredDate">-->
<!--                            <div class="block">-->
<!--                                <el-date-picker-->
<!--                                    clearable-->
<!--                                    v-model="requiredDate"-->
<!--                                    type="daterange"-->
<!--                                    unlink-panels-->
<!--                                    range-separator="To"-->
<!--                                    start-placeholder="Start date"-->
<!--                                    end-placeholder="End date"-->
<!--                                    :shortcuts="shortcuts"-->
<!--                                />-->
<!--                            </div>-->
<!--                        </el-form-item>-->
                        <el-form-item>
                            <el-button icon="search" type="primary"  @click="query">{{ $t('common.queryBtn') }}</el-button>
                            <el-button icon="refresh"  @click="resetQuery">{{ $t('common.resetBtn') }}</el-button>
                            <el-button icon="folder-add" type="success" @click="saveInfo"> {{ $t('SrmPoHeaderGroup.createDeliveryNote') }} </el-button>
                        </el-form-item>
                    </el-form>
                    <el-table :data="state.dataList" v-loading="state.loading" highlight-current-row border
                              :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
                              @row-click="clickRow" style="width: 100%;height: 100%;"
                              @selection-change="selectionChangeHandle">
                        <el-table-column type="selection" width="40" align="center" />
                        <el-table-column type="index" label="#" width="60"/>
                        <el-table-column prop="poCode" :label="$t('poheader.poCode')" show-overflow-tooltip/>
                        <el-table-column prop="poLine" :label="$t('podetail.poLine')" show-overflow-tooltip/>
                        <el-table-column prop="contractNumber" :label="$t('poheader.contractNumber')" show-overflow-tooltip/>
                        <el-table-column prop="materialCode" :label="$t('so.materialcode')" show-overflow-tooltip/>
                        <el-table-column prop="materialName" :label="$t('so.materialname')" show-overflow-tooltip/>
                        <el-table-column prop="spec" :label="$t('so.materialspec')" show-overflow-tooltip/>
                        <el-table-column prop="orderTotalNum" :label="$t('SrmPoHeaderGroup.orderTotalNum')" show-overflow-tooltip>
                            <template #default="scope">
                                <!--根据不同的状态选择不同的颜色的tag-->
                                <el-tag size="large" type='primary' >
                                    {{ scope.row.orderTotalNum }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="assignableNum" :label="$t('SrmPoHeaderGroup.assignableNum')" show-overflow-tooltip>
                            <template #default="scope">
                                <!--根据不同的状态选择不同的颜色的tag-->
                                <el-tag size="large" type='success' >
                                    {{ scope.row.assignableNum }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="requiredDate" :label="$t('SrmPoHeaderGroup.earliestDeliveryDate')" show-overflow-tooltip/>
                        <el-table-column prop="sendTotal" :label="$t('SrmPoHeaderGroup.sendTotal')" show-overflow-tooltip>
                            <template #default="scope">
                                <div v-if="scope.row.editable" style="width: 100%;height: 100%">
                                    <el-input-number
                                        v-model="scope.row.sendTotal"
                                        @blur="handleUpdateFinished(scope.row)"
                                        @change="checkQuantity(scope.row)"
                                        @keyup.enter="handleUpdateFinished(scope.row)"
                                        :min="0"
                                        :class="{ 'input-error': isError(scope.row) }"
                                    />
                                </div>
                                <div v-else>
                                    <span>{{ scope.row.sendTotal}}</span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="singleNum" :label="$t('SrmPoHeaderGroup.singleNum')" show-overflow-tooltip>
                            <template #default="scope">
                                <div v-if="scope.row.editable" style="width: 100%;height: 100%">
                                    <el-input-number
                                        v-model="scope.row.singleNum"
                                        @blur="handleUpdateFinished(scope.row)"
                                        @keyup.enter="handleUpdateFinished(scope.row)"
                                        :min="0"

                                    />
                                </div>
                                <div v-else>
                                    <span>{{ scope.row.singleNum}}</span>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                    <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle"
                                v-bind="state.pagination"/>
                </div>
            </pane>
            <pane size="50">
                <el-tabs model-value="first" class=" card-tabs" type="border-card">
                    <el-tab-pane name="first" class="">
                        <template #label>
                            <el-icon><calendar/></el-icon>
                            <span class="ml-0.5"> {{ $t('poheader.orderDetail') }} </span>
                        </template>
                        <srmPoHeaderGroupDetail ref="locationRef"/>
                    </el-tab-pane>
                </el-tabs>
            </pane>
        </splitpanes>

        <!-- 编辑、新增  -->
        <form-dialog ref="formDialogRef" @refresh="getDataList(false)"/>

    </div>
</template>

<script setup lang="ts" name="systemSrmPoheader">
import {BasicTableProps, useTable} from "/@/hooks/table";
import {poHeaderGroupList} from "/@/api/platform/srm/srmPodetail";
import srmPoHeaderGroupDetail from "/src/views/srm/srmPoHeaderGroup/srmPoHeaderGroupDetail/index.vue";
import {reactive, ref} from 'vue';
import {ElMessage} from "element-plus";

// 引入组件
const FormDialog = defineAsyncComponent(() => import('./form.vue'));
// 定义变量内容
const formDialogRef = ref()
const locationRef = ref()


// 在这里更新数据源
const handleUpdateFinished = (row) => {
    row.editable = false;
}

//判断输入数量不能大于送货单数量
const checkQuantity = (row) => {
    if (row.sendTotal > row.assignableNum) {
        row.sendTotal = row.assignableNum; // 重新调整当前行的值
        ElMessage({ message: `发货数量不能大于可分配数量 ${row.assignableNum}` });
    }
}
const isError = (row) => {
    return row.sendTotal > row.assignableNum;  // 返回是否超出可分配数量
}

const getYMD = (date:any) => {
    // 获取年份
    const year = date.getFullYear();

    // 获取月份，注意JavaScript中的月份是从0开始的，因此需要+1
    const month = String(date.getMonth() + 1).padStart(2, '0');

    // 获取日期
    const day = String(date.getDate()).padStart(2, '0');

    // 拼接成 yyyy-MM-dd 格式的字符串
    const formattedDate = `${year}-${month}-${day}`;

    return formattedDate;
};

const today = new Date();
const endDate = new Date(today);
endDate.setDate(today.getDate() - 6); // 今天之后的6天，总共一周
const requiredDate = ref([endDate, today]);

const shortcuts = [
    {
        text: 'Last week',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            return [start, end];
        },
    },
    {
        text: 'Last month',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            return [start, end];
        },
    },
    {
        text: 'Last 3 months',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            return [start, end];
        },
    },
];

// 搜索变量
const queryRef = ref()

const state: BasicTableProps = reactive<BasicTableProps>({
    pageList: poHeaderGroupList
})

const options = ref([
    { label: '全部', value: '' },
    { label: '订单开启', value: 'po_open' },
    { label: '订单关闭', value: 'po_close' },
]);

//  table hook
const {
    getDataList,
    currentChangeHandle,
    sizeChangeHandle,
    tableStyle
} = useTable(state)

// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
const selectedRows =ref([]) as any


// 多选事件
const selectionChangeHandle = (objs: { id: string }[]) => {
    selectObjs.value = objs.map(({id}) => id);
    multiple.value = !objs.length;
    selectedRows.value = objs;
};

//查询
const query = () => {
    // if (!requiredDate.value || !requiredDate.value[0]) {
    //     ElMessage.error('订单交期必填'); // 使用Element Plus的message组件提示用户
    //     return; // 如果开始时间未选，则不继续执行后续逻辑
    // }
    // state.queryForm.startDate = requiredDate.value ? getYMD(requiredDate.value[0]) : '';
    // state.queryForm.endDate = requiredDate.value ? getYMD(requiredDate.value[1]) : '';
    getDataList();
};

// 清空搜索条件
const resetQuery = () => {
    state.queryForm.status = "";
    state.queryForm.poCode = null;
    state.queryForm.contractNumber = null;
    // 清空日期选择器的值
    state.queryForm.purDate = [];
    // 清空搜索条件
    queryRef.value?.resetFields()
    getDataList(false)
}
// 点击行的时候触发
const clickRow = (row: any) => {
    locationRef.value.query(row)
    //遍历行是否可否可编辑
    state.dataList?.forEach(item =>{
        if(item.materialId == row.materialId){
            item.editable = true;
        }else {
            item.editable = false;
        }
    })
}
//创建送货单
const saveInfo = () =>{
    if(!selectedRows.value.length){
        ElMessage.error('请勾选数据');
        return;// 如果开始时间未选，则不继续执行后续逻辑
    }
    for (const item of selectedRows.value) {
        if (!item.sendTotal || !item.singleNum) {
            ElMessage.error('请填写发货数量，单包数量');
            return; // 这里的 return 会退出整个 submitForm 方法
        }
    }
    //打开弹框
    formDialogRef.value.openDialog(selectedRows.value)
}

</script>
<style scoped>
.input-error {
    border: 1px solid red; /* 标红的边框 */
    color: red;
}
</style>